package br.com.as.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.as.dominio.Fornecedor;
import br.com.as.utils.HibernateUtility;

/**
 * Classe para consistencia de fornecedor
 * 
 * @author msante
 *
 */
public class FornecedorDAO {

	@SuppressWarnings("unchecked")
	public  List<Fornecedor> listar() throws Exception{
		List<Fornecedor> lista = null;
		Session sessao = HibernateUtility.getSession();
		Transaction tx = null;
		try {
			tx = sessao.beginTransaction();
			Query query = sessao.createQuery(" from Fornecedor ");		
			lista = query.list();			
			tx.commit();			
		} catch (Exception e) {			
			tx.rollback();
			throw e;
		} finally {
			sessao.close();
		}
		return lista;
	}
	
	public  void incluir(Fornecedor fornecedor) throws Exception{
		Transaction tx = null;
		Session sessao = HibernateUtility.getSession();
		try {			
			tx = sessao.beginTransaction();
			sessao.save(fornecedor.getEndereco());
			sessao.save(fornecedor.getContato());
			sessao.save(fornecedor);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			sessao.close();
			throw e;
		}finally{
			sessao.close();	
		}
	}
	
	public  void alterar(Fornecedor fornecedor) throws Exception{
		Transaction tx = null;
		Session sessao = HibernateUtility.getSession();
		try {			
			tx = sessao.beginTransaction();
			sessao.saveOrUpdate(fornecedor.getEndereco());
			sessao.saveOrUpdate(fornecedor.getContato());
			sessao.update(fornecedor);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			sessao.close();
			throw e;
		}finally{
			sessao.close();	
		}
	}

	public void excluir(Fornecedor fornecedor) throws Exception{
		Transaction tx = null;
		Session sessao = HibernateUtility.getSession();
		try {			
			tx = sessao.beginTransaction();
			sessao.delete(fornecedor);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			sessao.close();
			throw e;
		}finally{
			sessao.close();	
		}
	}

	public  Fornecedor consultar(String cnpj) throws Exception{
		Fornecedor fornecedor = null;
		Session sessao = HibernateUtility.getSession();
		Transaction tx = null;
		try {
			tx = sessao.beginTransaction();
			Query query = sessao.createQuery("from Fornecedor cli where cli.cnpj =:cnpj");		
			query.setString("cnpj", cnpj);
			fornecedor = (Fornecedor) query.uniqueResult();			
			tx.commit();			
		} catch (Exception e) {			
			tx.rollback();
			throw e;
		} finally {
			sessao.close();
		}
		return fornecedor;		
	}

	public Fornecedor pesquisarPorId(Long id) throws Exception{
		Session sessao = HibernateUtility.getSession();
		try {
			Fornecedor temp = (Fornecedor) sessao.get(Fornecedor.class, id);
			return temp;
		} catch (Exception e) {			
			throw e;
		} finally {
			sessao.close();
		}
	}
	
}
